<template>
  <BasicDrawer 
    v-bind="$attrs" 
    @register="registerDrawer" 
    :title="getTitle" 
    width="900px" 
    @ok="handleSubmit" 
    showFooter destroyOnClose
  >
    <a-radio-group v-model:value="editModel" style="margin-bottom: 5px; margin-left: 20px;">
      <a-radio-button value="view">可视化编辑</a-radio-button>
      <a-radio-button value="script">脚本编辑</a-radio-button>
    </a-radio-group>
    <BasicForm @register="registerForm"/>

    <CodeEditor v-if="editModel == 'script'" v-model:value="policyContentStrRef" mode="application/json" />
    <template v-else v-for="(item, index) in policyFrom" :key="index">
      <PolicyStatement 
        :data="item" :policyStatement="policyStatementRef"
        :namespaceCode="apiNamespaceCode"
        @change-statement-list="handleChangePolicyStatement"
        :index="index" @delete="handleDeleteStatement" @copy="handleCopyStatement" 
      />
    </template>

    <template #footer>
<!--      <a-button @click="addStatement" v-if="editModel == 'view' && record.canWrite" type="primary" :disabled="disabled"  class="button-color-green">添加语句</a-button>-->
      <a-button @click="addStatement" type="primary" :disabled="disabled"  class="button-color-green">添加语句</a-button>
<!--      <a-button @click="handleSubmit" type="primary" v-if="record.canWrite" :disabled="disabled" :loading="loading">提交</a-button>-->
      <a-button @click="handleSubmit" type="primary" :disabled="disabled" :loading="loading">提交</a-button>
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, toRaw, computed, unref, useAttrs, watch } from "vue";
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { inputFormSchemas } from './data';
  import { CodeEditor } from "/@/components/CodeEditor"
  import { BasicDrawer, useDrawerInner} from '/@/components/Drawer';
  import { updateApiPermissionPolicy , getPermissionPolicy } from '/@/api/iam/permPolicy';
  import { useMessage } from '/@/hooks/web/useMessage';
  import PolicyStatement from './component/PolicyStatement.vue'
  import { ColEx } from '/@/components/Form/src/types';
  const { createMessage } = useMessage();

  const emit = defineEmits(['success', 'register']);
  const apiNamespaceCode = ref()
  const isUpdate = ref(true);
  const showBtn = ref(false);
  const record = ref<any>({});
  const policyStatementRef = ref<any[]>([])
  const policyFrom = ref<any[]>([])
  const loading = ref(false);
  const disabled = ref(false)
  const editModel = ref('script')
  const policyContentStrRef = ref()
  const policyContentRef = ref<any>({
    version: '1.0',
    statement: [
      {
        actions: [],
        condition: {}
      }
    ]
  })

  const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
    labelWidth: 90,
    schemas: inputFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  });

  watch(
    () => policyContentRef.value,
    (val) => {
      try {
        if (val && policyContentStrRef.value != JSON.stringify(val) ) {
          policyContentStrRef.value = JSON.stringify(policyContentRef.value)
        }
      } catch(e) {
        console.error(e)
      }
    },
    { deep: true },
  );

  watch(
    () => policyContentStrRef.value,
    (val : any) => {
      try {
        if (val && val != JSON.stringify(policyContentRef.value) ) {
          policyContentRef.value = JSON.parse(val)
        }
      } catch(e) {
        console.error(e, val)
      }
    },
    { deep: true },
  );


  const addStatement = () => {
    policyStatementRef.value.push({
      actions: [],
      condition: {}
    })
    const version = policyContentRef.value.version
    policyContentRef.value = {
      version,
      statement: unref(policyStatementRef.value)
    }
    policyFrom.value.push({
      show: true,
      title: '选择服务',
      actionCollapsible: 'disabled',
      statementIndex: policyStatementRef.value.length - 1
    })
  }

  const initStatement = () => {
    console.info('initStatement', record.value)
    const content = record.value.policyContent
    let index = 0;
    if (content.statement.length == 0) {
      addStatement()
      return
    }
    policyContentRef.value = {
      version: content.version,
      statement: unref(policyStatementRef.value)
    }
    content.statement.forEach(item => {
      policyStatementRef.value.push(item)

      const iamCode = item.actions.length > 0 ? item.actions[0].split(':')[0] : null
      policyFrom.value.push({
        show: true,
        title: iamCode ? `${iamCode} / ${item.actions.length} 个操作` : '选择服务',
        actionCollapsible: null,
        statementIndex: index++
      })
    })
    
  }

  const resetData = () => {
    policyStatementRef.value = []
    policyContentRef.value = { statement: [] }
    policyFrom.value = []
    disabled.value = false
  }
  
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    await resetFields();
    resetData()
    record.value = data.record
    apiNamespaceCode.value = data.apiNamespaceCode
    setDrawerProps({ confirmLoading: false, loading: true })

    try {
      record.value = await getPermissionPolicy({id: data.record.id, apiNamespaceCode: apiNamespaceCode.value,}) || {} 
      disabled.value = false
      initStatement()
      setFieldsValue({ ...record.value })
      setTimeout(() => showBtn.value = true, 10000)
    } finally {
      setDrawerProps({ loading: false})
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增权限策略' : '编辑权限策略'));

  const handleDeleteStatement = (index: number) => {
    const deletePolicy = policyFrom.value[index]
    policyFrom.value.splice(index, 1);
    policyFrom.value.filter(e => e.statementIndex > deletePolicy.statementIndex).forEach(e => e.statementIndex = e.statementIndex - 1)
    policyStatementRef.value.splice(deletePolicy.statementIndex, 1);
    const version = policyContentRef.value.version
    policyContentRef.value = { version, statement: unref(policyStatementRef.value) }
  }

  const handleCopyStatement = (data: any, index: number) => {
    const statementIndex = data.statementIndex as number;
    policyStatementRef.value.push(policyStatementRef.value[statementIndex])
    data.statementIndex = statementIndex + 1
    const version = policyContentRef.value.version
    policyContentRef.value = { version, statement: unref(policyStatementRef.value) }
    policyFrom.value.push(data)
  }
  async function handleSubmit() {
    try {
      loading.value = true;
      let values = await validate();
      setDrawerProps({confirmLoading: true});

      const content = unref(policyContentRef)
      console.log('content', content)
      if (!content || content.statement?.length == 0) {
        createMessage.warn('请添加语句')
        return
      }

      if (content.statement.findIndex(e => !e.actions || e.actions.length == 0) > -1) {
        createMessage.warn('请核对是否所有语句都已选择操作')
        return
      }

      const formData = { 
        ...values, 
        apiNamespaceCode: apiNamespaceCode.value,
        policyContent: content
      }
      console.log('formData', formData)

      await updateApiPermissionPolicy(formData);
      closeDrawer();
      createMessage.success(`${getTitle.value}成功`)
      emit('success');
    } finally {
      loading.value = false
      setDrawerProps({confirmLoading: false});
    }
  }

  const handleChangePolicyStatement = (v) => {
    console.log('change', v)
    policyStatementRef.value = v
    const version = policyContentRef.value.version
    policyContentRef.value = {
      version,
      statement: unref(policyStatementRef.value)
    }
  }
</script>

<style lang="less">
// .add-statement {
//   width: 100%;
//   margin-bottom: 20px;
// }
</style>
